package com.netease.nim.uikit.common.media.picker;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import com.netease.nim.uikit.R;
import com.netease.nim.uikit.business.session.module.Container;
import com.netease.nim.uikit.business.team.activity.AdvancedTeamInfoActivity;
import com.netease.nim.uikit.common.media.picker.loader.GlideImageLoader;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.common.util.storage.StorageType;
import com.netease.nim.uikit.common.util.storage.StorageUtil;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomMessageConfig;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangjun on 2015/9/22.
 */
public class PickImageHelper {

    private static final String TAG = "PickImageHelper";

    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;

    public static class PickImageOption {
        /**
         * 图片选择器标题
         */
        public int titleResId = R.string.choose;

        /**
         * 是否多选
         */
        public boolean multiSelect = true;

        /**
         * 最多选多少张图（多选时有效）
         */
        public int multiSelectMaxCount = 9;

        /**
         * 是否进行图片裁剪(图片选择模式：false / 图片裁剪模式：true)
         */
        public boolean crop = false;

        /**
         * 图片裁剪的宽度（裁剪模式时有效）
         */
        public int cropOutputImageWidth = 720;

        /**
         * 图片裁剪的高度（裁剪模式时有效）
         */
        public int cropOutputImageHeight = 720;

        /**
         * 图片选择保存路径
         */
        public String outputPath = StorageUtil.getWritePath(StringUtil.get32UUID() + ".jpg", StorageType.TYPE_TEMP);
    }

    /**
     * 打开图片选择器
     */
    public static void pickImage(final Context context, final int requestCode,
                                 final PickImageOption option, Container container) {
        if (context == null) {
            return;
        }
        checkSelfPermission(context, container, option);
    }

    //动态权限申请
    private static void checkSelfPermission(Context context, Container container, PickImageOption option) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // 提示用户如果想要正常使用，要手动去设置中授权。
                Toast.makeText(context, "请在 设置-应用管理 中开启此应用的储存授权。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions((Activity) context,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            // 进行正常操作
            selectImage(context, container, option);
        }
    }

    //图片选择部分
    private static void selectImage(final Context context, final Container container,
                                    final PickImageOption option) {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Log.i(TAG, "----------------- 选图开始 -----------------");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                LogUtil.i(TAG, photoList.toString());

                switch (option.titleResId) {
                    case 2131689628:
                        String s = photoList.get(0);
                        File pic = new File(s);
                        SnapChatAttachment snapChatAttachment = new SnapChatAttachment();
                        snapChatAttachment.setPath(pic.getPath());
                        snapChatAttachment.setSize(pic.length());
                        CustomMessageConfig config = new CustomMessageConfig();
                        config.enableHistory = false;
                        config.enableRoaming = false;
                        config.enableSelfSync = false;
                        IMMessage stickerMessage = MessageBuilder.createCustomMessage(container.account, container.sessionType, "阅后即焚消息", snapChatAttachment, config);
                        container.proxy.sendMessage(stickerMessage);
                        break;
                    default:
                        for (int i = 0; i < photoList.size(); i++) {
                            File file = new File(photoList.get(i));
                            IMMessage message = null;
                            if (container != null && container.sessionType == SessionTypeEnum.ChatRoom) {
                                message = ChatRoomMessageBuilder.createChatRoomImageMessage(container.account, file, file.getName());
                            } else {
                                if (container != null) {
                                    message = MessageBuilder.createImageMessage(container.account, container.sessionType, file, file.getName());
                                }
                            }
                            if (container != null) {
                                container.proxy.sendMessage(message);
                            } else {
                                if (context instanceof AdvancedTeamInfoActivity) {
                                    ((AdvancedTeamInfoActivity) context).updateTeamIcon(photoList.get(i));
                                }
                            }
                        }
                        break;
                }
            }

            @Override
            public void onCancel() {
                Log.i(TAG, "用户已取消");
            }

            @Override
            public void onFinish() {
                Log.i(TAG, "----------------- 选图结束 -----------------");
            }

            @Override
            public void onError() {
                Log.e(TAG, "----------------- 选图异常 -----------------");
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .maxSize(option.multiSelectMaxCount)                // 最大图片选择数量
                .multiSelect(option.multiSelect)                    // 是否多选   默认：false
                .crop(option.crop, 1, 1, option.cropOutputImageWidth, option.cropOutputImageHeight)                                  // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open((Activity) context);
    }
}
